import React, { Component } from 'react'
import {connect} from 'react-redux'
import { getArticleDetail, getCommentList, publishComment } from './store/actions.js'
import { Redirect } from 'react-router-dom'
import styles from './styles.less'
import withStyle from '../../withStyle'
import {withRouter } from 'react-router';
import parse from 'url-parse'
import cx from 'classnames'
import axios from 'axios'

const colorList = [
	"#64492b",
	"#ac6767",
	"#1d953f",
	"#ef4136",
	"#375830",
	"#78331e",
	"#f15a22",
	"#6c4c49",
	"#2570a1",
	"#bed742"
]

class PostArticle extends Component {

	// 渲染评论
	renderComment(commentList) {
		return commentList.map(item => {
			return (
				<div key={item._id} className={styles.commentWrapper}>
					<div className={styles.vcard}>
						<img src={`../../assets/img/avatar_${Math.floor(Math.random()*10) + 1}.png`} alt=""/>
						<div className={styles.vright}>
							<div className={styles.vheader}>{item.nickName || 'anonymous'}</div>
							<div className={styles.vtime}>
								<span>{item.time || '未知时间'}</span>
								<span className={styles.reply} onClick={()=> {this.props.toggleDialog(true, item._id)}}>回复</span>
							</div>
							<div className={styles.vcontent}>{item.content}</div>
						</div>
					</div>
					{
						item.children && item.children.map((item1, index) => {
							return (
								<div key={index} className={styles.childrenWrapper}>
									<div className={styles.vcard}>
										<img src={`../../assets/img/avatar_${Math.floor(Math.random()*10) + 1}.png`} alt=""/>
										<div className={styles.vright}>
											<div className={styles.vheader}>{item1.nickName || 'anonymous'}</div>
											<div className={styles.vtime}>
												<span>{item1.time || '未知时间'}</span>
												<span className={styles.reply} onClick={()=> {this.props.toggleDialog(true, item._id)}}>回复</span>
											</div>
											<div className={styles.vcontent}>{item1.content}</div>
										</div>
									</div>	
								</div>
							)
						})
					}
				</div>
			)
		})
	}

	computCommentNum(commentList) {
		let total = commentList.length
		commentList.forEach(item => {
			if(item.children) {
				total += item.children.length
			}
		})
		return total
	}

	componentDidMount() {
		let E = window.wangEditor
		let editor = new E('#toolbar', '#content')  // 两个参数也可以传入 elem 对象，class 选择器
		editor.customConfig.zIndex = 64
		editor.create()
		editor.$textElem.attr('contenteditable', false)
		// 获取文章详情
		let { query } = parse(this.props.location.search, true)
		this.props.doGetArticleDetail(query.id)
		this.props.doGetCommentList(query.id)

		// 百度分享代码初始化
		console.log(111)
		window._bd_share_config = { "common": { "bdSnsKey": {}, "bdText": "finnwu", "bdMini": "2", "bdPic": "", "bdStyle": "0", "bdSize": "16" }, "share": {}, "image": { "viewList": ["qzone", "tsina", "tqq", "renren", "weixin"], "viewText": "分享到：", "viewSize": "16" }, "selectShare": { "bdContainerClass": null, "bdSelectMiniList": ["qzone", "tsina", "tqq", "renren", "weixin"] } }
		let src = '/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5)
		// let node = document.getElementsByTagName('head')[0] || document.body
		axios.get(src).then(function(res) {
			console.log('success')
			var data = res.data.replace('"', '\"')
			eval(data)
		})
	}

	render() {
		return (
			<div className={styles.postArticle}>
				<div className={styles.header}></div>
				<div className={styles.container}>
					<div className={styles.post}>
						<div id="toolbar" style={{display: 'none'}}></div>
						<h1 className={styles.postTitle}>{this.props.articleDetail.articleTitle}</h1>
						<div className={styles.postMeta}>
							{this.props.articleDetail.articleTime}
						</div>
						<div id="content" className={styles.postContent}>
							<div dangerouslySetInnerHTML={{__html: this.props.articleDetail.articleContent}} />
						</div>
						<div className={styles.add}>
							<span>最后更新时间  {this.props.articleDetail.articleTime}</span><br/>
							<span>原文链接  <a href={"http://www.finnwu.cn" + this.props.location.pathname + this.props.location.search}>{"http://www.finnwu.cn" + this.props.location.pathname + this.props.location.search}</a></span>
						</div>
						<div className={styles.pageReward}>
						{
							this.props.mask && (
								<div className={styles.content}>
									<p className={styles.title}>请我吃辣条</p>
									<img style={{width: 200,height:200}} src="../../assets/img/winxin.png" alt=""/>
								</div>
							)
						}
							<span onClick={() => {this.props.toggleMask(true)}}>赏</span>
						</div>
						<div className={styles.postFooter}>
						{/* 分享模块 */}
							<div className={styles.pageShareWrap}>
								<span className={cx(styles.share, "bdsharebuttonbox", 'bdshare-button-style0-16')}>
									<a className="bds_more" style={{ marginLeft: "13px",marginTop: "12px"}} data-cmd="more">
									</a>
								</span>
							</div>
							{this.props.articleDetail.articleTag && this.props.articleDetail.articleTag.map((item, index) => {
								return <div className={styles.tagItem} key={item} style={{backgroundColor: colorList[index]}}>{item}</div>
							})}
						</div>
					</div>
					<div className={styles.comment}>
						<div className={styles.vwrapper}>
							<div className={styles.vheader}>
								<input  type="text" placeholder="昵称" onChange={(e) => {this.props.handleChange('nickName', e.target.value)}}/>
								<input type="mail" placeholder="邮箱" onChange={(e) => {this.props.handleChange('email', e.target.value)}}/>
							</div>
							<div className={styles.veditor}>
								<textarea name="" id="" cols="30" rows="10" placeholder="要不要说点什么" onChange={(e) => {this.props.handleChange('content', e.target.value)}}></textarea>
							</div>
							<div className={styles.vbutton}>
								<span onClick={() => {this.props.doPublishComment({...this.props.commentForm, _id: this.props.articleDetail._id})}}>回复</span>
							</div>
						</div>
						<div className={styles.vcommentNum}>
							<span>{this.computCommentNum(this.props.commentList)}</span>评论
						</div>

						{ this.renderComment(this.props.commentList) }
						
					</div>
				</div>
				{this.props.mask && <div className={styles.mask} onClick={() => {this.props.toggleMask(false)}}></div> }
				{this.props.dialog && <div className={styles.mask} onClick={() => {this.props.toggleDialog(false)}}></div>}
				{
					this.props.dialog && 
					<div className={styles.dialog}>
						<div className={styles.box}>
							<div className={styles.title}>回复<i className="iconfont icon-close" style={{float: 'right', cursor: "pointer"}} onClick={()=> {this.props.toggleDialog(false)}}></i></div>
							<div className={styles.content}>
								<label className={styles.label}>昵称</label>
								<input type="text" className={styles.input} onChange={(e) => {this.props.handleChange('nickName', e.target.value)}}/>
								<label className={styles.label} >email</label>
								<input type="text" className={styles.input} onChange={(e) => {this.props.handleChange('email', e.target.value)}}/>
								<label className={styles.label}>内容</label>
								<textarea  className={styles.input} onChange={(e) => {this.props.handleChange('content', e.target.value)}}/>
							</div>
							<div className={styles.footer}>
								<span className={cx(styles.btn, styles.summit)} onClick={() => this.props.doPublishComment(
									{...this.props.commentForm, _id: this.props.articleDetail._id, parentID: this.props.replyId}
									)}>回复</span>
								<span className={cx(styles.btn, styles.cancle)} onClick={()=> {this.props.toggleDialog(false)}}>取消</span>
							</div>
						</div>
					</div>
				}
			</div>
		)
	}
}



const mapState = (state) => ({
	articleDetail: state.postArticle.articleDetail,
	mask: state.postArticle.mask,
	commentList: state.postArticle.commentList,
	commentForm: state.postArticle.commentForm,
	dialog: state.postArticle.dialog,
	replyId: state.postArticle.replyId
})

const mapDispatch = (dispatch) => ({
	doGetArticleDetail(id) {
		dispatch(getArticleDetail(id))
	},
	toggleMask(value) {
		dispatch({type: 'change_mask', value: value})
	},
	doGetCommentList(id) {
		dispatch(getCommentList(id))
	},
	handleChange(valueType, value) {
		dispatch({type: 'change_commentForm', valueType, value})
	},
	doPublishComment(data) {
		if(!data.content) {
			alert('请输入内容！')
			return
		}
		dispatch(publishComment(data)).then(res => {
			if(res.data.resultCode + '' === '0') {
				alert('评论成功！')
				dispatch(getCommentList(res.data.data.articleId))
				dispatch({type: 'change_dialog', value: false})
			}
		})
	},
	toggleDialog(value, replyId) {
		dispatch({type: 'change_dialog', value: value, replyId})
	}
})

let PostArticleOut = connect(mapState, mapDispatch)(withStyle(PostArticle, styles))

PostArticleOut.loadData = (store, req) => {
	return store.dispatch(getArticleDetail(req.query.id))
}

export default withRouter(PostArticleOut)